<template>
  <div class="cart-web">
    <div class="cart-contain">
      <div class="cart-table-container">
        <div class="cart-filter-bar">
          <span class="switch-cart">购物车</span>
        </div>

        <div v-if="showEmptyCart" class="empty-cart">
          <p class="empty-cart-text">购物车为空</p>
        </div>

          <div v-else>
          <el-table :data="cartList" size="mini" style="width: 95%; margin: 0 auto">
            <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
            <el-table-column label="封面图片" width="180">
              <template slot-scope="scope">
                <el-image
                    :src="JSON.parse(scope.row.pictures)[0].url"
                    style="width: 120px; height: 120px"
                >
                  <div slot="placeholder" class="image-slot">
                    Loading<span class="dot">...</span>
                  </div>
                  <div slot="error" class="image-slot">
                    <el-image
                        style="width: 120px; height: 120px"
                        src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                    ></el-image>
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="title" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="150" header-align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" size="mini" @change="updateQuantity(scope.row)"
                                 :min="1"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="小计" prop="price" width="120"></el-table-column>
            <el-table-column label="操作" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button size="medium" type="danger" v-on:click="delGood(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          </div>
        </div>
        <div class="cart-filter-bar-bottom">
          <div class="cart-sum">
            <span class="total-text">合计：</span>
            <span ref="totalPriceSpan" class="total-symbol">{{ cartList.length > 0 ? cartList[0].totalPrice : 0 }}</span>
            <el-button type="primary" round="true" @click="generateOrders()">结算</el-button>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
export default {
  name: "shopCart",
  data() {
    return {
      cartList: [],

      showEmptyCart: false,

      refreshed: false
    };
  },
  methods: {

    getList() {
      let cartInfo = JSON.parse(localStorage.getItem("cart"));
      let url = 'http://localhost:14001/cartItem/list-by-cart?cartId=' + cartInfo.id;
      console.log('url = ' + url);
      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .get(url)
          .then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.cartList = jsonResult.data;
              this.$message.success('成功获取购物车列表');
            } else {
              this.$message.error('获取购物车列表失败');
            }
          })
          .catch((error) => {
            console.log(error);
          })
          .finally(() => {
            this.showEmptyCart = this.cartList.length === 0;
          });
    },

    delGood(id) {
      let url = 'http://localhost:14001/cartItem/deleteById?id=' + id;
      console.log('url = ' + url);
      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .get(url)
          .then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.getList();
              this.$message.success('成功删除商品');
            } else {
              this.$message.error('删除商品失败');
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },

    updateQuantity(row) {
      let url = 'http://localhost:14001/cartItem/update-quantity?id=' + row.id + '&quantity=' + row.quantity;
      console.log('url = ' + url);
      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .get(url)
          .then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.getList()
              this.$message.success('成功更新数量');
            } else {
              this.$message.error('更新数量失败');
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },

    generateOrders() {
      if (this.cartList.length === 0) {
        this.$confirm('购物车为空', '提示', {
          confirmButtonText: '确定',
          type: 'info',
        });
        return;
      }

      let cartInfo = JSON.parse(localStorage.getItem("cart"));
      let url = 'http://localhost:14001/shopping-cart/updateState?cartId=' + cartInfo.id + "&stateId=" + 2;
      console.log('url = ' + url);
      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .post(url)
          .then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.$router.push('/sys-user/product/orders')
            }
          })
    },
  },
  mounted() {
    this.getList();
  },
};
</script>

<style scoped>

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.empty-cart-image {
  width: 200px;
  height: 200px;
}

.empty-cart-text {
  margin-top: 10px;
  font-size: 16px;
  color: #909399;
}

.cart-web {
  margin-top: 20px;
  width: 100%;
}

.cart-contain {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  background: #f5f7fa;
}

.cart-table-container {
  background-color: #fff;
  padding: 20px;
}

.cart-filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.switch-cart {
  font-size: 16px;
  font-weight: bold;
}

.cart-list-content {
  margin-bottom: 20px;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  background-color: #f5f7fa;
  color: #909399;
}

.image-slot .dot {
  animation: dotDot 1.4s infinite;
}

@keyframes dotDot {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.cart-filter-bar-bottom {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
}

.cart-sum {
  display: flex;
  align-items: center;
}

.total-text {
  font-size: 16px;
  font-weight: bold;
}

.total-symbol {
  font-size: 24px;
  font-weight: bold;
  margin-right: 10px;
}

.el-input-number__decrease,
.el-input-number__increase {
  background-color: #f5f7fa;
  color: #909399;
}

.el-input-number__decrease:hover,
.el-input-number__increase:hover {
  background-color: #e4e7ed;
  color: #606266;
}

.el-input-number__decrease:active,
.el-input-number__increase:active {
  background-color: #d3d4d6;
  color: #303133;
}
</style>